package com.zxl.yjb.activity.my;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.zxl.yjb.R;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.AddressBookBean;
import com.zxl.yjb.bean.AreaBean;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.GetPositionUtil;
import com.zxl.yjb.utils.TestAddressProvider;
import com.zxl.yjb.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.AddressSelector;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

public class PositionAddActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_page_title)
    TextView tvPageTitle;
    @BindView(R.id.tv_position)
    TextView tv_position;
    @BindView(R.id.ll_position)
    LinearLayout llPosition;
    @BindView(R.id.ll_location)
    LinearLayout llLocation;
    @BindView(R.id.ll_name)
    LinearLayout llName;
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;
    @BindView(R.id.et_location)
    EditText etLocation;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;

    private DataManager dataManager;

    private List<AreaBean> provinceList = new ArrayList<>();

    private String longitude = "";
    private String latitude = "";
    private String mProvince = "";
    private String mCity = "";
    private String mCountry = "";
    private String mDistrict = "";
    private String mStreet = "";
    private String mOthers = "";
    private String mName = "";
    private String mPhone = "";

    private String id = "";
    private AddressBookBean.DataBean dataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_position);
        id = getIntent().getStringExtra("id");
        dataBean = (AddressBookBean.DataBean) getIntent().getSerializableExtra("dataBean");
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void initView() {
        if (TextUtils.isEmpty(id))
            tvPageTitle.setText("添加地址");
        else
            tvPageTitle.setText("编辑地址");

        if (dataBean != null) {
            tv_position.setText(dataBean.getProvince() + " " + dataBean.getCity() + " " + dataBean.getDistrict() + " " + dataBean.getStreet());
            etLocation.setText(dataBean.getOthers());
            etName.setText(dataBean.getName());
            etPhone.setText(dataBean.getPhone());
        }
    }

    @OnClick({R.id.iv_back, R.id.ll_position, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_position:
                if (provinceList != null && provinceList.size() != 0) {
                    setAddress(provinceList);
                } else {
                    /*dataManager = new DataManager();
                    observerOnNextListener = new ObserverOnNextListener<List<AreaBean>>() {
                        @Override
                        public void onNext(List<AreaBean> provinceBeanList) {
                            provinceList = provinceBeanList;
                            setAddress(provinceList);
                        }
                    };
                    dataManager.getAreaAllProvince(new ProgressObserver<List<AreaBean>>(observerOnNextListener, this), new HashMap<String, String>());*/
                    GetPositionUtil.getPosition(PositionAddActivity.this, "", new GetPositionUtil.SearchResult() {
                        @Override
                        public void onResult(DistrictResult districtResult) {

                        }

                        @Override
                        public void onListResult(List<AreaBean> list) {
                            provinceList = list;
                            setAddress(provinceList);
                        }
                    });

                }
                break;
            case R.id.tv_save:
                mOthers = etLocation.getText().toString();
                mName = etName.getText().toString();
                mPhone = etPhone.getText().toString();
                if (TextUtils.isEmpty(mOthers)) {
                    ToastUtils.show(PositionAddActivity.this, "请填写详细地址");
                    return;
                }

                if (TextUtils.isEmpty(mName)) {
                    ToastUtils.show(PositionAddActivity.this, "请填写姓名");
                    return;
                }

                if (TextUtils.isEmpty(mPhone)) {
                    ToastUtils.show(PositionAddActivity.this, "请填写手机号");
                    return;
                }

                getLonLat();
                break;
        }
    }

    /**
     * 设置地址
     *
     * @param provinceList
     */
    private void setAddress(List<AreaBean> provinceList) {
        AddressSelector selector = new AddressSelector(this);
        selector.setAddressProvider(new TestAddressProvider(provinceList, PositionAddActivity.this));

        final BottomDialog dialog = new BottomDialog(this);
        selector.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                String s =
                        (province == null ? "" : province.name) +
                                (city == null ? "" : " " + city.name) +
                                (county == null ? "" : " " + county.name) +
                                (street == null ? "" : " " + street.name);
                tv_position.setText(s);
                mCountry = "中华人民共和国";
                mProvince = province.name;
                mCity = city.name;
                mDistrict = county.name;
                mStreet = street.name;

                dialog.cancel();
            }
        });
        ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.addContentView(selector.getView(), layout);
        dialog.show();
    }


    private void getLonLat() {


        GeocodeSearch geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                if (i == 1000 && geocodeResult.getGeocodeAddressList().size() > 0) {
                    longitude = geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint().getLongitude() + "";
                    latitude = geocodeResult.getGeocodeAddressList().get(0).getLatLonPoint().getLatitude() + "";
                    if (TextUtils.isEmpty(id))
                        addAddress();
                    else
                        updateAddress();
                } else {
                    ToastUtils.show(PositionAddActivity.this, "经纬度查询失败，请输入准确的地址");
                }
            }
        });
        // name表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode
        GeocodeQuery query = new GeocodeQuery(mOthers, mCity);
        geocoderSearch.getFromLocationNameAsyn(query);
    }


    private void addAddress() {
        dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("lon", longitude);
        map.put("lat", latitude);
        map.put("province", mProvince);
        map.put("city", mCity);
        map.put("country ", mCountry);
        map.put("district", mDistrict);
        map.put("street", mStreet);
        map.put("others", mOthers);
        map.put("name", mName);
        map.put("phone", mPhone);
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object o) {
                ToastUtils.show(PositionAddActivity.this, "添加成功");
                finish();
            }
        };
        dataManager.addressBook_add(new ProgressObserver<Object>(listener, this), map);
    }

    private void updateAddress() {
        dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        map.put("lon", longitude);
        map.put("lat", latitude);
        map.put("province", mProvince);
        map.put("city", mCity);
        map.put("country ", mCountry);
        map.put("district", mDistrict);
        map.put("street", mStreet);
        map.put("others", mOthers);
        map.put("name", mName);
        map.put("phone", mPhone);
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object o) {
                ToastUtils.show(PositionAddActivity.this, "编辑成功");
                finish();
            }
        };
        dataManager.addressBook_add(new ProgressObserver<Object>(listener, this), map);
    }
}
